'use strict';

const BaseService = require('./base');

class ReservationService extends BaseService {
  constructor(ctx) {
    super(ctx, 'Reservation');
  }

  // 重写getPage方法，增加会员和美食信息
  async getPage(where, page, pageSize) {
    const { app } = this.ctx;
    const include = [{
      model: app.model.Member,
      as: 'member',
      attributes: ['id', 'nickname', 'phone'],
    }, {
      model: app.model.Food,
      as: 'food',
      attributes: ['id', 'name', 'price'],
    }];
    return super.getPage(where, page, pageSize, include);
  }

  // 创建预定
  async createReservation(data) {
    const { ctx, app } = this;
    const { foodId, reserveDate, personCount } = data;

    // 检查美食库存
    const hasStock = await ctx.service.food.checkStock(foodId, reserveDate, personCount);
    if (!hasStock) {
      ctx.throw(400, '该日期预定人数已满');
    }

    // 获取美食信息计算金额
    const food = await app.model.Food.findByPk(foodId);
    if (!food || food.status !== 1) {
      ctx.throw(400, '美食不存在或已下架');
    }

    // 创建预定订单
    data.amount = food.price * personCount;
    return await super.create(data);
  }

  // 获取会员的预定列表
  async getMemberReservations(memberId, status) {
    const { app } = this.ctx;
    const where = { memberId };
    if (status !== undefined) {
      where.status = status;
    }
    return await app.model.Reservation.findAll({
      where,
      include: [{
        model: app.model.Food,
        as: 'food',
        attributes: ['id', 'name', 'price', 'image'],
      }],
      order: [['createdAt', 'DESC']],
    });
  }
}

module.exports = ReservationService;
